package com.hk.kindheartedness;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者病历处理
 */
public class CaseHistoryActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private String loginUserId;

    private ListView querySubscribeInfoListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_case_history);
//        实例化
        dbOpenHelper = new DBOpenHelper(CaseHistoryActivity.this, "db_kindheartedness", null, 1);
//        获取ListView控制权
        querySubscribeInfoListView = findViewById(R.id.querySubscribeInfoListView);
//      提取出登录用户名
        final Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
        loginUserId = bundle.getString("loginUserId");
//        通过当前登录用户Id查询预约记录
        findByPatientId(loginUserId);

        //        获取ListView点击事件并进行处理
        querySubscribeInfoListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                获取选项中的HashMap对象
                HashMap<String, String> map = (HashMap<String, String>) querySubscribeInfoListView.getItemAtPosition(position);
                final String registrationLogId = map.get("registrationLogId");
                Log.i("获取的预约编号为:",registrationLogId);
                // TODO: 2022/3/27 编写取消预约
                /**
                 * 1、通过Id查询到病历信息
                 */
                //        建立一个对话框
//                添加一个弹出对话框
                AlertDialog alertDialog = new AlertDialog.Builder(CaseHistoryActivity.this).create();
//                设置提示
                alertDialog.setMessage("是否查看就诊病历？");
//                设置 确认按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                      1、查询当前患者已就诊是否开具了病历
                        Cursor queryCaseHistory = readableDatabase.query("case_history", null, "registration_log_id = ?", new String[]{registrationLogId}, null, null, null);
                        String caseHistoryId = null;
                        while (queryCaseHistory.moveToNext()) {
                            caseHistoryId = queryCaseHistory.getString(0);
                        }
                        if (caseHistoryId == null) {
                            toast = ToastUtil.toastHint(toast, CaseHistoryActivity.this, "病历暂未出具,请稍等！");
                            return;
                        }
                        bundle.putString("registrationLogId",registrationLogId);
                        intent = new Intent(CaseHistoryActivity.this,CaseHistoryInfoActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
//        设置取消按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toast = ToastUtil.toastHint(toast, CaseHistoryActivity.this, "本次操作已取消！");
                        return;
                    }
                });
//          显示对话框
                alertDialog.show();

            }
        });


    }

    /**
     * 查询当前用户的挂号预约记录
     * @param loginUserId 用户Id
     */
    private void findByPatientId(String loginUserId) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "user_id = ? and is_see_a_doctor = 1", new String[]{loginUserId}, null, null, null);
        while (queryRegistrationLog.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
//            患者预约记录Id
            String registrationLogId = queryRegistrationLog.getString(0);
//            挂号记录ID
            String registrationId = queryRegistrationLog.getString(2);
//            预约时间
            String subscribeTime = queryRegistrationLog.getString(3);
//            状态（默认 false:0 未就诊）
            String isSeeADoctor = queryRegistrationLog.getString(4);
            isSeeADoctor =  Integer.valueOf(isSeeADoctor) == 0 ? "未就诊" : "已就诊";
            map.put("registrationLogId",registrationLogId);
//            年月日
            String substring = subscribeTime.substring(0, 10);
//            时分秒
            String substring2 = subscribeTime.substring(11);
            map.put("subscribeTime",substring+"\n"+substring2);
            map.put("isSeeADoctor",isSeeADoctor);
//            通过挂号记录Id查询挂号费用和就诊时间
            Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "id = ?", new String[]{registrationId}, null, null, "registration_date asc");
            String registrationDate = null,registrationTime = null,registrationMoney = null;
            while (queryRegistrationSetting.moveToNext()) {
                registrationDate = queryRegistrationSetting.getString(2);
                registrationTime = queryRegistrationSetting.getString(3);
                registrationMoney = queryRegistrationSetting.getString(6);
            }
            map.put("registrationDate",registrationDate+"\n"+registrationTime);
            map.put("registrationMoney",registrationMoney);
            resultList.add(map);
        }
        //        判断是否具有预约记录
        if (resultList == null || resultList.size() == 0) {
//            toast = ToastUtil.toastHint(toast, CaseHistoryActivity.this, "暂时没有就诊哦，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                CaseHistoryActivity.this,
                resultList,
                R.layout.query_patient_subscribe_info,
                new String[]{
                        "registrationLogId",
                        "subscribeTime", "registrationDate",
                        "registrationMoney", "isSeeADoctor"
                },
                new int[]{
                        R.id.registrationLogId,
                        R.id.subscribeDateTime, R.id.registrationDateTime,
                        R.id.registrationMoney, R.id.isSeeADoctor
                }
        );
        querySubscribeInfoListView.setAdapter(simpleAdapter);

    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}